/**
 * 棋盘工具函数
 */

import { BOARD_SIZE, isValidPosition } from '../constants/positions.js';

/**
 * 检查两点之间的路径是否畅通（不包括起点和终点）
 */
export function isPathClear(from, to, board) {
  const { row: fromRow, col: fromCol } = from;
  const { row: toRow, col: toCol } = to;

  // 计算方向向量
  const rowDir = toRow === fromRow ? 0 : (toRow > fromRow ? 1 : -1);
  const colDir = toCol === fromCol ? 0 : (toCol > fromCol ? 1 : -1);

  // 如果不是直线移动，返回false
  if (rowDir !== 0 && colDir !== 0) {
    return false;
  }

  // 检查路径上是否有阻挡
  let currentRow = fromRow + rowDir;
  let currentCol = fromCol + colDir;

  while (currentRow !== toRow || currentCol !== toCol) {
    if (board[currentRow][currentCol] !== null) {
      return false; // 路径被阻挡
    }
    currentRow += rowDir;
    currentCol += colDir;
  }

  return true;
}

/**
 * 计算两点之间路径上的棋子数量（不包括起点和终点）
 */
export function countPiecesInPath(from, to, board) {
  const { row: fromRow, col: fromCol } = from;
  const { row: toRow, col: toCol } = to;

  // 计算方向向量
  const rowDir = toRow === fromRow ? 0 : (toRow > fromRow ? 1 : -1);
  const colDir = toCol === fromCol ? 0 : (toCol > fromCol ? 1 : -1);

  // 如果不是直线移动，返回-1表示无效
  if (rowDir !== 0 && colDir !== 0) {
    return -1;
  }

  let count = 0;
  let currentRow = fromRow + rowDir;
  let currentCol = fromCol + colDir;

  while (currentRow !== toRow || currentCol !== toCol) {
    if (board[currentRow][currentCol] !== null) {
      count++;
    }
    currentRow += rowDir;
    currentCol += colDir;
  }

  return count;
}

/**
 * 获取两点之间的所有位置（不包括起点和终点）
 */
export function getPathPositions(from, to) {
  const { row: fromRow, col: fromCol } = from;
  const { row: toRow, col: toCol } = to;
  const positions = [];

  // 计算方向向量
  const rowDir = toRow === fromRow ? 0 : (toRow > fromRow ? 1 : -1);
  const colDir = toCol === fromCol ? 0 : (toCol > fromCol ? 1 : -1);

  let currentRow = fromRow + rowDir;
  let currentCol = fromCol + colDir;

  while (currentRow !== toRow || currentCol !== toCol) {
    positions.push({ row: currentRow, col: currentCol });
    currentRow += rowDir;
    currentCol += colDir;
  }

  return positions;
}

/**
 * 计算两点之间的曼哈顿距离
 */
export function getManhattanDistance(from, to) {
  return Math.abs(from.row - to.row) + Math.abs(from.col - to.col);
}

/**
 * 计算两点之间的切比雪夫距离（棋盘距离）
 */
export function getChebyshevDistance(from, to) {
  return Math.max(Math.abs(from.row - to.row), Math.abs(from.col - to.col));
}

/**
 * 检查位置是否在指定矩形区域内
 */
export function isInRectangle(position, topLeft, bottomRight) {
  const { row, col } = position;
  return row >= topLeft.row && row <= bottomRight.row &&
         col >= topLeft.col && col <= bottomRight.col;
}

/**
 * 获取指定位置周围的所有有效位置
 */
export function getAdjacentPositions(position, includeCenter = false) {
  const { row, col } = position;
  const positions = [];

  for (let r = row - 1; r <= row + 1; r++) {
    for (let c = col - 1; c <= col + 1; c++) {
      if (!includeCenter && r === row && c === col) continue;
      if (isValidPosition(r, c)) {
        positions.push({ row: r, col: c });
      }
    }
  }

  return positions;
}

/**
 * 获取指定位置四个正交方向的位置
 */
export function getOrthogonalPositions(position) {
  const { row, col } = position;
  const positions = [];
  const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];

  for (const [dRow, dCol] of directions) {
    const newRow = row + dRow;
    const newCol = col + dCol;
    if (isValidPosition(newRow, newCol)) {
      positions.push({ row: newRow, col: newCol });
    }
  }

  return positions;
}

/**
 * 获取指定位置四个对角方向的位置
 */
export function getDiagonalPositions(position) {
  const { row, col } = position;
  const positions = [];
  const directions = [[-1, -1], [-1, 1], [1, -1], [1, 1]];

  for (const [dRow, dCol] of directions) {
    const newRow = row + dRow;
    const newCol = col + dCol;
    if (isValidPosition(newRow, newCol)) {
      positions.push({ row: newRow, col: newCol });
    }
  }

  return positions;
}

/**
 * 在指定方向上查找第一个棋子
 */
export function findFirstPieceInDirection(from, direction, board, maxDistance = BOARD_SIZE.ROWS) {
  const { row: fromRow, col: fromCol } = from;
  const [rowDir, colDir] = direction;

  let currentRow = fromRow + rowDir;
  let currentCol = fromCol + colDir;
  let distance = 1;

  while (isValidPosition(currentRow, currentCol) && distance <= maxDistance) {
    const piece = board[currentRow][currentCol];
    if (piece) {
      return {
        piece,
        position: { row: currentRow, col: currentCol },
        distance
      };
    }
    currentRow += rowDir;
    currentCol += colDir;
    distance++;
  }

  return null;
}

/**
 * 获取棋盘上所有空位置
 */
export function getEmptyPositions(board) {
  const positions = [];

  for (let row = 0; row < BOARD_SIZE.ROWS; row++) {
    for (let col = 0; col < BOARD_SIZE.COLS; col++) {
      if (board[row][col] === null) {
        positions.push({ row, col });
      }
    }
  }

  return positions;
}

/**
 * 获取棋盘上指定颜色的所有棋子位置
 */
export function getPiecePositions(board, color) {
  const positions = [];

  for (let row = 0; row < BOARD_SIZE.ROWS; row++) {
    for (let col = 0; col < BOARD_SIZE.COLS; col++) {
      const piece = board[row][col];
      if (piece && piece.color === color) {
        positions.push({ 
          row, 
          col, 
          piece 
        });
      }
    }
  }

  return positions;
}

/**
 * 检查两个位置是否相等
 */
export function positionsEqual(pos1, pos2) {
  return pos1.row === pos2.row && pos1.col === pos2.col;
}

/**
 * 将位置转换为字符串表示（用于哈希或比较）
 */
export function positionToString(position) {
  return `${position.row},${position.col}`;
}

/**
 * 从字符串解析位置
 */
export function stringToPosition(str) {
  const [row, col] = str.split(',').map(Number);
  return { row, col };
}

/**
 * 将棋盘转换为字符串表示（用于调试或存储）
 */
export function boardToString(board) {
  return board.map(row => 
    row.map(piece => piece ? piece.symbol : '·').join(' ')
  ).join('\n');
}

/**
 * 复制棋盘
 */
export function cloneBoard(board) {
  return board.map(row => 
    row.map(piece => piece ? { ...piece, position: { ...piece.position } } : null)
  );
}
